package cn.eud.hunau.service.impl;

import cn.eud.hunau.exception.BusinessException;
import cn.eud.hunau.mapper.UserMapper;
import cn.eud.hunau.pojo.User;
import cn.eud.hunau.request.RegisterReq;
import cn.eud.hunau.request.UserReq;
import cn.eud.hunau.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author hb
 * @date 2025-06-18 16:34:00
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserReq reqObject) {

        User user=  userMapper.queryByUserNameAndPassword(reqObject.getUsername(),reqObject.getPassword());

        //业务逻辑的判断
        if(user==null){
            throw new BusinessException("用户名或密码错误",400401);
        }
        return user;
    }

    @Override
    public void register(RegisterReq registerReq) {
        // 检查用户名是否已存在
        if (userMapper.countByUsername(registerReq.getUsername()) > 0) {
            throw new BusinessException("用户名已存在", 400400);
        }

        // 检查两次密码是否一致
        if (!registerReq.getPassword().equals(registerReq.getConfirmPassword())) {
            throw new BusinessException("两次密码输入不一致", 400401);
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(registerReq.getUsername());
        user.setPassword(registerReq.getPassword());
        user.setPet_type(registerReq.getPetType());
        user.setPet_age(registerReq.getPetAge());
        user.setPet_health(registerReq.getPetHealth());
        user.setCreate_time(LocalDateTime.now());

        // 插入用户
        int result = userMapper.insertUser(user);
        if (result <= 0) {
            throw new BusinessException("注册失败，请稍后重试", 500500);
        }
    }



}
